package com.qc.blogsystemplus.controller.admin;

import com.qc.blogsystemplus.bean.ResponseBean;
import com.qc.blogsystemplus.bean.UserBean;
import com.qc.blogsystemplus.entity.User;
import com.qc.blogsystemplus.service.UserService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin")
public class AdUserController {


    @Autowired
    private UserService userService;

    @RequiresRoles("admin")
    @GetMapping("/getalluser")
    public ResponseBean getUser(){
        List<User> userList = userService.getAllUser();
        return new ResponseBean(200,"查询成功",userList);
    }

    @RequiresRoles("admin")
    @GetMapping("/deluser")
    public ResponseBean delUser(@RequestParam("username")String username){
        int re = userService.delUser(username);
        if (re != 0) {
            return new ResponseBean(200, "用户" + username + "已被删除", null);
        } else {
            return new ResponseBean(401,"删除失败",null);
        }
    }

    @RequiresRoles("admin")
    @PostMapping("/updateuser")
    public ResponseBean updateUser(@RequestBody UserBean userBean) {
        int re = userService.updateUser(userBean);
        if (re != 0){
            return new ResponseBean(200,"更新成功",userService.getUser(userBean.getUsername()));
        } else {
            return new ResponseBean(401,"更新失败",null);
        }
    }

    @RequiresRoles("admin")
    @PostMapping("/adduser")
    public ResponseBean addUser(@RequestBody UserBean userBean){
        User userDb = userService.getUser(userBean.getUsername());
        if (userDb != null){
            return new ResponseBean(401,"该用户名存在，不能重复",null);
        }

        int re = userService.addUser(userBean);
        if (re != 0) {
            return new ResponseBean(200,"添加用户成功",userService.getUser(userBean.getUsername()));
        } else {
            return new ResponseBean(401,"添加用户失败",null);
        }
    }
}
